﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using popLib;
using System.Collections;
using PhotoMgr.src.database;
using PhotoMgr.src.common;

namespace PhotoMgr.src.gui.contest
{
    public partial class ContestDetail : Form
    {
        public int ID { get; set; }

        public int IDNhanDoi { get; set; }

        public bool inDGV { get; set; }

        public Contest Record { get; set; }

        public FormAction Action { get; set; }

        public FormValidation FormValidator { get; set; }

        public List<Round> DataSource;
        public List<ContestUser> DataSourceX;

        public bool UpdateMode { get; set; }

        public bool IsDatabaseChanged { get; set; }

        public string FormTitle { get; set; }

        public ContestDetail(FormAction action, object id)
        {
            InitializeComponent();

            Action = action;

            ID = NumberLib.getInt(id);

            UpdateMode = true;

            this.Icon = PhotoMgr.Properties.Resources.logo32;
        }

        public ContestDetail(FormAction action, int id)
        {
            InitializeComponent();

            Action = action;

            ID = id;

            UpdateMode = true;

            this.Icon = PhotoMgr.Properties.Resources.logo32;
        }

        public ContestDetail(FormAction action)
        {
            InitializeComponent();

            Action = action;

            UpdateMode = false;

            this.Icon = PhotoMgr.Properties.Resources.logo32;
        }

        #region Event Functions
        private void ContestDetail_Load(object sender, EventArgs e)
        {
            FormLoad();
        }
        private void btn_add_Click(object sender, EventArgs e)
        {
            ButtonAdd();
        }

        private void btn_update_Click(object sender, EventArgs e)
        {
            ButtonUpdate();
        }

        private void btn_dispose_Click(object sender, EventArgs e)
        {
            ButtonDispose();
        }

        private void btn_confirm_Click(object sender, EventArgs e)
        {
            ButtonConfirm();
        }

        private void btn_save_Click(object sender, EventArgs e)
        {
            ButtonSave();
        }

        private void btn_cancel_Click(object sender, EventArgs e)
        {
            ButtonCancel();
        }

        private void ToaThuoc_Detail_Load(object sender, EventArgs e)
        {
            FormLoad();
        }

        private void btn_print_Click(object sender, EventArgs e)
        {
            ButtonPrint();
        }
        #endregion

        enum ContestEnum { STT, RoundLevel, RoundID, ContestID, RoundCapacity, DateCreated, Status };
        enum UserEnum { STT, UserID, ContestUserID, Username, Fullname, ContestName, SettingName };

        #region Handle Functions
        public virtual void FormLoad()
        {
            //init default value here
            FormTitle = "Chi tiết cuộc thi";
            DataSource = new List<Round>();
            DataSourceX = new List<ContestUser>();

            dgv_list.AutoGenerateColumns = false;
            Global.InitDataGridView(dgv_list, new DataGridViewColumn[] { 
                Global.GenColumn("STT").SetAlign(DataGridViewContentAlignment.MiddleCenter).SetFrozen(true).SetVisible(false),
                Global.GenColumn("Vòng",                            "RoundLevel"),
                Global.GenColumn("Vòng ID",                         "RoundID").SetVisible(false),
                Global.GenColumn("ID Constest",                     "ContestID").SetVisible(false),
                Global.GenColumn("Số lượng hình ảnh cho phép",      "RoundCapacity").SetForeColor(Color.Blue).SetSizeMode(DataGridViewAutoSizeColumnMode.Fill),
                Global.GenColumn("Ngày tạo",                        "DateCreated").SetFormat("dd/MM/yyyy"),
                Global.GenColumn("Tình trạng",                      "Status"),
            });

            dgv_user.AutoGenerateColumns = false;
            Global.InitDataGridView(dgv_user, new DataGridViewColumn[] { 
                Global.GenColumn("STT").SetAlign(DataGridViewContentAlignment.MiddleCenter).SetFrozen(true),//.SetVisible(false),
                Global.GenColumn("ID người dùng",                       "UserID").SetVisible(false).SetForeColor(Color.Blue).SetReadOnly(true),
                Global.GenColumn("ContestUserID",                       "ContestUserID").SetVisible(false).SetReadOnly(true),
                Global.GenColumn("Tài khoản",                           "Username").SetReadOnly(true),
                Global.GenColumn("Tên người tham gia",                  "Fullname").SetSizeMode(DataGridViewAutoSizeColumnMode.Fill).SetReadOnly(true),
                Global.GenColumn("Tên cuộc thi",                        "ContestName").SetVisible(false),
                Global.GenColumn("Thiết lập chung",                     "SettingName").SetVisible(false),
                });

            //init default data
            Global.InitStatusCombobox(Status, Global.StatusType.ContestStatus, false);
            DBManager.Fill_Setting(SettingID, false);

            //DBManager.Fill....

            InitFormValidation();

            ViewDetail();

            UpdateFormAction();
            
            dgv_list.AllowUserToResizeColumns = true;
            dgv_list.AllowUserToResizeRows = false;
            dgv_list.MultiSelect = false;
        }

        public virtual void ButtonUpdate()
        {
            FormValidator.ChangeState(FormValidation.FormState.UpdateCurrent);

            
            //Not allow to Add or Delete Rows
            //dgv_list.AllowUserToAddRows = true;
            //dgv_list.AllowUserToDeleteRows = true;
        }

        public virtual void ButtonDispose() {
            
        }

        public virtual void ButtonAdd()
        {
            //change mode and hide all buttons
            btn_update.Visible = false;
            btn_add.Visible = false;            
            btn_confirm.Visible = true;
            UpdateMode = false;            


            Record = new Contest();
            dgv_list.Rows.Clear();
            dgv_user.Rows.Clear();

            Record.Status = "M";
            txNguoiTao.Text = UserAccount.Instance.Username;
            //TinhTrang.SelectedValue = "M";

            FormValidator.ChangeState(FormValidation.FormState.CreateNew);

            //set default value in form
            DataSource.Clear();
            DataSourceX.Clear();

            dgv_list.Rows.Clear();
            
            
        }

        public void ThemDuLieu()
        {
        }

        public virtual void ButtonConfirm() 
        {
            if (Global.FormMessage(Global.FormMessageType.ConfirmAccept, new string[] { "cuộc thi ", txContestName.Text }).Success)
            {
                Status.SelectedValue = "A";

                ButtonSave();

                ViewDetail();

                UpdateFormAction();

                dgv_list.AllowUserToAddRows = false;
            }
        }

        public virtual void ButtonCancel()
        {
            if (UpdateMode)
            {
                FillData();
                Search(1);
                FormValidator.ChangeState(FormValidation.FormState.Ready);
            }
            else
            {
                this.Close();
            }
        }

        public void ExecuteViewDetail(object ID)
        {
            if (FormValidator.CurrentFormState == FormValidation.FormState.Ready)
            {
                this.ID = NumberLib.getInt(ID);

                UpdateMode = true;

                ViewDetail();

                UpdateFormAction();
            }
            else
            {
                FormLib.alert("Bạn đang cập nhật/thêm mới thông tin!!\r\nXin vui lòng hoàn tất trước khi xem chứng từ khác.", "Thông báo");
            }
        }
                
        public virtual void ButtonSave()
        {
            if (!StringLib.isValid(txContestName.Text))
                return;
            if (!FormValidator.Validate())
                return;
            
            Contest current = new Contest();
            current.ContestID = Record.ContestID;
            current.ContestName = txContestName.Text;
            current.DateStart = cbNgayBatDau.Values;
            current.DateEnd = cbNgayKetThuc.Values;
            current.SettingID = 1;
            current.DateCreated = Global.GetServerDateTime();
            current.Note = Global.GetString(txGhiChu.Text);
            current.Status = Status.SelectedValue.ToString();            
            current.OwnUserID = UpdateMode ? Record.OwnUserID : UserAccount.Instance.UserID;

            DataSource.Clear();
            for (int i = 0; i < dgv_list.Rows.Count; i++)
            {
                var RoundItem = new Round();

                RoundItem.ContestID = Record.ContestID;
                RoundItem.RoundID = NumberLib.getInt(dgv_list.Rows[i].Cells[(int)ContestEnum.RoundID].Value);
                RoundItem.RoundLevel = NumberLib.getInt(dgv_list.Rows[i].Cells[(int)ContestEnum.RoundLevel].Value);
                RoundItem.RoundCapacity = NumberLib.getInt(dgv_list.Rows[i].Cells[(int)ContestEnum.RoundCapacity].Value);
                RoundItem.DateCreated = Global.GetServerDateTime();
                RoundItem.Status = "A";

                DataSource.Add(RoundItem);
            }

            DataSourceX.Clear();

            for (int i = 0; i < dgv_user.Rows.Count; i++)
            {
                var ContestItem = new ContestUser();

                ContestItem.ContestUserID = NumberLib.getInt(dgv_user.Rows[i].Cells[(int) UserEnum.ContestUserID].Value);
                ContestItem.ContestID = Record.ContestID;
                ContestItem.UserID = NumberLib.getInt(dgv_user.Rows[i].Cells[(int)UserEnum.UserID].Value);

                DataSourceX.Add(ContestItem);
            }

            ReturnSet rs = DBManager.Save_Contest(UpdateMode, current, Record, DataSource, DataSourceX);

            if (rs.Success)
            {
                Record = current;
                IsDatabaseChanged = true;
                FormValidator.ChangeState(FormValidation.FormState.Ready);
                dgv_list.AllowUserToAddRows = false;

                //Testinng
                Record = DBManager.Detail_Contest(Record.ContestID);
                ID = Record.ContestID;
                FillData();
                Search(1);

                UpdateMode = true;
                UpdateFormAction();
            }
            else
            {
                Global.FormMessageType messageType = UpdateMode ? Global.FormMessageType.UpdateFail : Global.FormMessageType.AddFail;
                Global.FormMessage(messageType, new string[] { "Thông tin cuộc thi", txContestName.Text }, null, (Global.DBErrorType)rs.Result);
            }
        }

        public static bool ReturnCellValue(System.Windows.Forms.DataGridView datagrid, int rows, int sothutu)
        {
            if (datagrid.Rows[rows].Cells[sothutu].Value == null)
            {
                return false;
            } else {
                if ((bool)datagrid.Rows[rows].Cells[sothutu].Value.Equals(true))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }

        public virtual void UpdateFormAction()
        {
            int userID = NumberLib.getInt(Record.OwnUserID);
            String username = DBManager.GetUsername(userID);

            //btn_dispose.Visible = Action.DisposeRecord;
            btn_save.Visible = Action.EditRecord || Action.AddRecord;
            btn_add.Visible = Action.AddRecord;

            //depend on UpdateMode 

            btn_save.Visible = Action.EditRecord || Action.EditRecordOwner || Action.AddRecord;
            btn_add.Visible = Action.AddRecord;

            //depend on UpdateMode 
            if (Action.EditRecord == true) //EditRecord == true -> free to edit any record
                btn_update.Visible = UpdateMode && Record.Status == "O";
            else if (Action.EditRecordOwner == true) //EditRecordOwner == true -> if NguoiTao == username -> allow to edit
                btn_update.Visible = UpdateMode && Record.OwnUserID == UserAccount.Instance.UserID && Record.Status == "O";

            if (Action.ConfirmRecord == true) //ConfirmRecord == true -> free to confirm any record
                btn_confirm.Visible = Record.Status == "O";
            else if (Action.DisposeRecordOwner == true) //DisposeRecordOwner == true -> if NguoiTao == username -> allow to dispose
                btn_confirm.Visible = username == UserAccount.Instance.Username && Record.Status == "O";

            //if (Action.DisposeRecord == true) //DisposeRecord == true -> free to dispose any record
            //    btn_dispose.Visible = UpdateMode && Record.Status == "A";
            //else if (Action.DisposeRecordOwner == true) //DisposeRecordOwner == true -> if NguoiTao == username -> allow to dispose
            //    btn_dispose.Visible = UpdateMode && username == UserAccount.Instance.Username && Record.Status == "A";

            //btn_confirm.Visible = Action.ConfirmRecord && Record.TinhTrang == "M";
            btn_confirm.Visible = Record.Status == "O";

            if (Status.SelectedIndex >= 0 && Status.SelectedValue.ToString() == "A")
            {
                btn_update.Visible = false;
            }

            //btn_dispose.Visible = Action.DisposeRecord && UpdateMode && Record.TinhTrang == "XN";
            //btn_dispose.Visible = UpdateMode && Record.Status == "A";

            //btn_print.Visible = UpdateMode && Record.Status == "A";

            //update shortcutkey for button
            //Global.InitDetailFormButton(this, btn_add, btn_update, btn_confirm, btn_dispose, btn_cancel, btn_save, btn_print);
            Global.InitDetailFormButton(this, btn_add, btn_update, btn_confirm, new Button(), btn_cancel, btn_save, new Button());
            //btn_print.Text = "In biến phí(F7)";
            //btn_dispose.Text = "Hủy biến phí(F4)";
        }

        public virtual void InitFormValidation()
        {
            FormValidator = new FormValidation(this);
            FormValidator.AddHandleContainer(flp_container);
            FormValidator.AddHandleControl(dgv_list);
            FormValidator.AddHandleControl(txRoundCap);
            
            FormValidator.InitNavigatorForm(btn_add, btn_update, new Button(), btn_save, btn_cancel, btn_confirm, new Button());
            FormValidator.FormStateChanged += new FormValidation.FormStateChangeEvent(FormStateChanged);

            //init validation here
            FormValidator.ValidateText(txContestName, true, 3, -1);
            FormValidator.ValidateFromToDate(cbNgayBatDau, cbNgayKetThuc, false, "Ngày bắt đầu phải trước ngày bắt đầu của cuộc thi!!!");

            //Global.InitDetailFormButton(this, btn_add, btn_update, btn_confirm, btn_dispose, btn_cancel, btn_save, btn_print);

            cbNgayTao.Enabled = false;            

            FormValidator.AddHandleControlExceptLock(Status);            
            FormValidator.AddHandleControlExceptLock(cbNgayTao);
            FormValidator.AddHandleControlExceptLock(txNguoiTao);

            this.KeyDown += delegate(object sender, KeyEventArgs e)
            {
                switch (e.KeyCode)
                {
                    case Keys.Enter:
                        if (inDGV)
                        {
                            WindowLib.PressKey(Keys.Tab);
                        }
                        break;
                }
            };
        }

        public virtual void FormStateChanged(FormValidation.FormState state)
        {
            switch (state)
            {
                default:
                case FormValidation.FormState.Ready:
                    this.Text = FormTitle;
                    break;
                case FormValidation.FormState.CreateNew:
                    this.Text = FormTitle + " - Thêm mới";
                    break;
                case FormValidation.FormState.UpdateCurrent:
                    this.Text = FormTitle + " - Cập nhật";
                    break;
            }
        }

        public virtual void ViewDetail()
        {

            if (UpdateMode)
            {
                //Bổ sung
                Contest result = DBManager.Detail_Contest(ID);
                Record = (Contest)result;
                FillData();

                
            }
            else
            {
                ButtonAdd();
            }
        }

        public virtual void ViewDetail(int NhanDoi)
        {

        }

        public virtual void FillData()
        {
            if (Record == null) return;

            if (Record.ContestName == null) return;

            txContestName.Text = Record.ContestName;
            cbNgayBatDau.Values = (DateTime) Record.DateStart;
            cbNgayKetThuc.Values = (DateTime)Record.DateEnd;
            txNguoiTao.Text = DBManager.User_GetNameFromID((int)Record.OwnUserID);
            //TenDichVuEHosp.Text = Record.TenDichVu_eHosp.ToString();
            //MaDichVu.Text = Record.MaDichVu.ToString();

            //TenDichVu.Text = Record.TenDichVu.ToString();
            //NguoiCapNhat.Text = Record.NguoiCapNhat.ToString();
            //NguoiHuy.Text = Record.NguoiCapNhat;
            //LyDoHuy.Text = Record.LyDoHuy != null ? Record.LyDoHuy.ToString() : "-";

            //if (Record.MaLoaiBienPhi.Trim() == "MT")
            //{
            //    MaLoaiBienPhi.SelectedIndex = 0;
            //}
            //else if (Record.MaLoaiBienPhi.Trim() == "TTCT")
            //{
            //    MaLoaiBienPhi.SelectedIndex = 1;
            //}
            //else if (Record.MaLoaiBienPhi.Trim() == "DSLT")
            //{
            //    MaLoaiBienPhi.SelectedIndex = 2;
            //}

            //LyDoHuy.Text = Record.LyDoHuy != null ?Record.LyDoHuy : "-";
            txGhiChu.Text = Record.Note != null ? Record.Note : "";
            Status.SelectedValue = Record.Status;
            Search(1, Record.ContestID);

            //SapXepVongThi();

            //FillDetail(Record.ContestID);

            Search(1);
        }

        public virtual void FillDetail(int Contest_ID)
        {

        }

        public virtual void Search(int page)
        {
            dgv_list.Rows.Clear();
            List<Round> result = DBManager.SearchRound(ID);

            int STT = 1;
            foreach (var item in result)
            {
                dgv_list.Rows.Add(new object[] { STT.ToString(), item.RoundLevel, item.RoundID, item.ContestID, item.RoundCapacity, item.DateCreated, Global.GetStatusName(item.Status) });
                STT++;
            }

            dgv_user.Rows.Clear();

            List<View_ContestUserSetting> userList = DBManager.SearchContestUserSetting(ID);

            int STTX = 1;
            foreach (var item in userList)
            {
                dgv_user.Rows.Add(new object[] { STTX.ToString(), item.UserID, item.ContestUserID, item.Username, item.Fullname, item.ContestName, item.SettingName });
                STT++;
            }

            SapXepVongThi();
        }

        public virtual void Search(int page, int SearchID)
        {
            dgv_list.Rows.Clear();
            List<Round> result = DBManager.SearchRound(SearchID);

            //enum UserEnum { STT, UserID, ContestUserID, Username, Fullname, ContestName, SettingName };

            int STT = 1;
            foreach (var item in result)
            {
                dgv_list.Rows.Add(new object[] { STT.ToString(), item.RoundID, item.RoundLevel, item.RoundCapacity, item.ContestID, item.DateCreated, Global.GetStatusName(item.Status) });
                STT++;
            }

            dgv_user.Rows.Clear();
            List<View_ContestUserSetting> userList = DBManager.SearchContestUserSetting(SearchID);

            //enum UserEnum { STT, UserID, Username, Fullname, ContestName, SettingName };

            int STTX = 1;
            foreach (var item in userList)
            {
                dgv_user.Rows.Add(new object[] { STTX.ToString(), item.UserID, item.ContestUserID, item.Username, item.Fullname, item.ContestName, item.SettingName });
                STT++;
            }

            SapXepVongThi();
        }

        public virtual void ButtonPrint() 
        {
            //List<ReportData_ToaThuoc> source = new List<ReportData_ToaThuoc>();
            //foreach (DataGridViewRow row in dgv_list.Rows)
            //{
            //    if (row.Cells[0].Value != null)
            //    {
            //    }
            //}

            //using (var a = new Report_ToaThuoc(source)
            //{
            //    NgayGioIn = Global.GetServerDateTime().ToGioNgayString(),
            //    NguoiLap = UserAccount.Instance.TenNhanVien,
            //    TenBenhNhan = TenBenhNhan.Text.ToUpper(),
            //    MaToa = StringLib.Replace1time(TenDichVu.Text, "-TTRV", ""),
            //    HA = HA.Text == "-" ? "-" : HA.Text.Contains("mmHg")? HA.Text : HA.Text + "mmHg" ,
            //    TanSoTim = TanSoTim.Text == "0" ? "0" : TanSoTim.Text + " lần/phút",
            //    Tuoi = Tuoi.Text,

            //})
            //{
            //    a.ShowDialog();
            //}
        }
        #endregion

        private void dgv_list_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {                                    
        }

        private void dgv_list_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if (e.ColumnIndex == (int)ContestEnum.RoundCapacity)
                {
                    if (dgv_list.Rows[e.RowIndex].Cells[(int)ContestEnum.RoundCapacity].Value != null)
                    {
                        dgv_list.Rows[e.RowIndex].Cells[(int)ContestEnum.RoundCapacity].Value = NumberLib.getDouble(dgv_list.Rows[e.RowIndex].Cells[(int)ContestEnum.RoundCapacity].Value);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString() + " right here");
            }
        }

        private void dgv_list_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            if (e.Control is DataGridViewComboBoxEditingControl)
            {
                ((ComboBox)e.Control).DropDownStyle = ComboBoxStyle.DropDown;
                ((ComboBox)e.Control).AutoCompleteSource = AutoCompleteSource.ListItems;
                ((ComboBox)e.Control).AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.Suggest;
            }
        }

        private void ToaThuoc_Detail_FormClosing(object sender, FormClosingEventArgs e)
        {
            FormClose(e);
        }

        public virtual void FormClose(FormClosingEventArgs e)
        {
            if (FormValidator.CurrentFormState != FormValidation.FormState.Ready)
            {
                if (!Global.FormMessage(Global.FormMessageType.ConfirmCancel, "Nhập Liệu Biến Phí").Success)
                {
                    e.Cancel = true;
                    return;
                }
            }
        }

        private void dgv_list_Enter(object sender, EventArgs e)
        {
            this.Tag = false;
            inDGV = true;
        }

        private void dgv_list_Leave(object sender, EventArgs e)
        {
            this.Tag = true;
            inDGV = false;
        }

        private void dgv_list_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13) txGhiChu.Focus(); 
            {
            }
        }

        public static string checkString(object obj)
        {
            if (obj != null)
            {
                return obj.ToString();
            }
            else
            {
                return "";
            }
        }

        public static String checkStr(object obj)
        {
            if (obj != null)
            {
                return obj.ToString();
            }
            else
            {
                return "0";
            }
        }

        private void btn_copy_Click(object sender, EventArgs e)
        {
            ButtonCopy();
        }

        public virtual void ButtonCopy(int IDnhandoi)
        {
            //change mode and hide all buttons
            btn_update.Visible = false;
            //btn_add.Visible = false;
            //btn_dispose.Visible = false;
            btn_confirm.Visible = true;

            UpdateMode = false;

            int ID_tam = IDnhandoi;
            FormValidator.ChangeState(FormValidation.FormState.CreateNew);

            //set default value in form
            //BienPhi itemTam = DBManager.Detail_BienPhi(ID_tam);

            //TenDichVu.Text = itemTam.TenDichVu;
            //TenDichVuEHosp.Text = itemTam.TenDichVu_eHosp;
            //MaDichVu.Text = itemTam.MaDichVu;
            //NgayCapNhat.Text = itemTam.NgayCapNhat.Value.ToString();

            //String tinhtranghientai = TinhTrang.SelectedValue.ToString();
            //if (tinhtranghientai == "H")
            //{
            //    gbx_cotainer.Height = 210;

            //    dgv_list.Location = new Point(dgv_list.Location.X, dgv_list.Location.Y - 75);
            //    dgv_list.Height = 295;
            //}

            //Record = new BienPhi();

            //Record.TinhTrang = "M";
            //TinhTrang.SelectedValue = "M";
        }

        public virtual void ButtonCopy()
        {
            //change mode and hide all buttons
            btn_update.Visible = false;
            //btn_add.Visible = false;
            //btn_dispose.Visible = false;
            btn_confirm.Visible = true;
            UpdateMode = false;
            //Record = new KhungGiaBHYT();

            int ID_tam = this.ID;
            FormValidator.ChangeState(FormValidation.FormState.CreateNew);

            //set default value in form

            var itemTam = DBManager.Detail_Contest(ID);

            //txGhiChu.Text = "";
            //txGhiChu.Text = itemTam.ContestName;
            //NguoiCapNhat.Text = UserAccount.Instance.Username;

            String tinhtranghientai = Status.SelectedValue.ToString();

            if (tinhtranghientai == "H")
            {
                gbx_cotainer.Height = 112;

                dgv_list.Location = new Point(dgv_list.Location.X, dgv_list.Location.Y - 75);
                dgv_list.Height = 396;
            }

            Record = new Contest();

            Record.Status = "M";
            Status.SelectedValue = "M";
        }

        private void btn_add_VisibleChanged(object sender, EventArgs e)
        {
            //btn_copy.Visible = btn_add.Visible;
        }

        private void btn_add_EnabledChanged(object sender, EventArgs e)
        {
            //btn_copy.Enabled = btn_add.Enabled;
        }

        public virtual void FillCopyData(int IDCopy)
        {
            this.IDNhanDoi = IDCopy;
        }

        private double CalculateTotalDrugSpecial(DateTime NgayTN, int SoNgayHenTaiKham, double SLUongThu2, double SLUongThu3, double SLUongThu4, double SLUongThu5, double SLUongThu6, double SLUongThu7, double SLUongCN)
        {
            double TotalDrug = 0;

            TotalDrug += SLUongThu2 * GetTotalDayDrugByDayOfWeek(NgayTN, SoNgayHenTaiKham, DayOfWeek.Monday);
            TotalDrug += SLUongThu3 * GetTotalDayDrugByDayOfWeek(NgayTN, SoNgayHenTaiKham, DayOfWeek.Tuesday);
            TotalDrug += SLUongThu4 * GetTotalDayDrugByDayOfWeek(NgayTN, SoNgayHenTaiKham, DayOfWeek.Wednesday);
            TotalDrug += SLUongThu5 * GetTotalDayDrugByDayOfWeek(NgayTN, SoNgayHenTaiKham, DayOfWeek.Thursday);
            TotalDrug += SLUongThu6 * GetTotalDayDrugByDayOfWeek(NgayTN, SoNgayHenTaiKham, DayOfWeek.Friday);
            TotalDrug += SLUongThu7 * GetTotalDayDrugByDayOfWeek(NgayTN, SoNgayHenTaiKham, DayOfWeek.Saturday);
            TotalDrug += SLUongCN * GetTotalDayDrugByDayOfWeek(NgayTN, SoNgayHenTaiKham, DayOfWeek.Sunday);

            TotalDrug = Math.Ceiling(TotalDrug);

            return TotalDrug;
        }

        public static int GetTotalDayDrugByDayOfWeek(DateTime NgayTN, int SoNgayHenTaiKham, DayOfWeek day)
        {
            int TongNgayUongThuoc = SoNgayHenTaiKham;
            DateTime NgayUongThuocCuoi = NgayTN.AddDays(TongNgayUongThuoc);
            TongNgayUongThuoc = (int)NgayUongThuocCuoi.Subtract(NgayTN).TotalDays;

            DateTime CheckDate;
            int counter = 0;
            for (int i = 0; i < TongNgayUongThuoc; i++)
            {
                CheckDate = NgayTN.AddDays(i);

                if (CheckDate.DayOfWeek == day)
                {
                    counter++;
                }
            }
            return counter;
        }

        public static double CheckNum(bool coUongThuoc, double slHangNgay)
        {
            if (coUongThuoc)
            {
                return slHangNgay;
            }
            return 0;
        }

        private void AddDV_Click(object sender, EventArgs e)
        {
            //dynamic form = new Form();
            //FormAction action = new FormAction(false, true, false, false, false, true);

            //form = new DM_DichVu_List(action);
            //form.ShowDialog();

            //if (form.SelectedItem == null)
            //{
            //    return;
            //}

            //object SelectedObject = form.SelectedItem;
            //string maThuoc = form.SelectedID.ToString();
            //string TenThuoc = form.SelectedItem.TenDichVu.ToString();
            //int MathuocDV = form.SelectedItem.DichVu_ID;

            //TenDichVu.Text = TenThuoc;
        }

        private void TenDichVuEHosp_SelectedIndexChanged(object sender, EventArgs e)
        {
            //MaDichVu.Text = TenDichVuEHosp.SelectedValue.ToString();
            //if (MaDichVu.Text != "")
            //{
            //    TenDichVu.Text = DBManager.GetTenDichVuFromEhosp(MaDichVu.Text);
            //}
        }

        private void TinhTrang_SelectedIndexChanged(object sender, EventArgs e)
        {
            String tinhtranghientai = Status.SelectedValue.ToString();

            //if (tinhtranghientai == "M")
            //{
            //    gbx_cotainer.Height = 141;

            //    //dgv_list.Location = new Point(dgv_list.Location.X, dgv_list.Location.Y - 75);
            //    dgv_list.Height = 367;
            //}

            //if (tinhtranghientai == "H")
            //{
            //    gbx_cotainer.Height = 112;

            //    dgv_list.Location = new Point(dgv_list.Location.X, dgv_list.Location.Y - 75);
            //    dgv_list.Height = 396;
            //}
        }

        

        private void button1_Click(object sender, EventArgs e)
        {
            int roundLevel = dgv_list.RowCount + 1;
            int RoundCap = NumberLib.getInt(txRoundCap.Text);
            
            if (RoundCap < 1)
            {
                MessageBox.Show("Không thể tạo vòng không có người tham gia !!!", "Thông báo");
                return;
            }

            for (int i = 0; i < dgv_list.Rows.Count; i++)
            {
                if (RoundCap == NumberLib.getInt(dgv_list.Rows[i].Cells[(int)ContestEnum.RoundCapacity].Value))
                {
                    MessageBox.Show("Không thể tạo vòng thi có số lượng giống nhau !!!", "Thông báo");
                    return;
                }
            }

            DateTime timeNow = Global.GetServerDateTime();
            String StatusX = "A";

            dgv_list.Rows.Add(new object[] { roundLevel, roundLevel, 0, ID, RoundCap, timeNow, Global.GetStatusName(StatusX) });

            SapXepVongThi();
        }

        private void SapXepVongThi()
        {
            List<ContestItem> mylist = new List<ContestItem>();

            for (int i = 0; i < dgv_list.Rows.Count; i++)
            {
                ContestItem item = new ContestItem(NumberLib.getInt(dgv_list.Rows[i].Cells[(int)ContestEnum.STT].Value),
                    NumberLib.getInt(dgv_list.Rows[i].Cells[(int)ContestEnum.RoundLevel].Value),
                    NumberLib.getInt(dgv_list.Rows[i].Cells[(int)ContestEnum.RoundID].Value),
                    NumberLib.getInt(dgv_list.Rows[i].Cells[(int)ContestEnum.ContestID].Value),
                    NumberLib.getInt(dgv_list.Rows[i].Cells[(int)ContestEnum.RoundCapacity].Value),
                    (DateTime)dgv_list.Rows[i].Cells[(int)ContestEnum.DateCreated].Value,
                    Global.GetString(dgv_list.Rows[i].Cells[(int)ContestEnum.Status].Value));
                mylist.Add(item);
            }

            mylist = mylist.OrderByDescending(x => x.RoundCapacity).ToList<ContestItem>();

            dgv_list.Rows.Clear();

            foreach (var item in mylist)
            {
                dgv_list.Rows.Add(new object[] {item.STT, item.VongThi, item.VongID, item.ContestID, item.RoundCapacity, item.DateCreated, Global.GetStatusName(item.Status) });
            }

            for (int i = 0; i < dgv_list.Rows.Count; i++)
            {
                dgv_list.Rows[i].Cells[(int)ContestEnum.STT].Value = i + 1;
                dgv_list.Rows[i].Cells[(int)ContestEnum.RoundLevel].Value = i + 1;
            }

            for (int i = 0; i < dgv_user.Rows.Count; i++)
            {
                dgv_user.Rows[i].Cells[(int)UserEnum.STT].Value = i + 1;
            }
        }
                
        private void dgv_list_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            bt_suavong.PerformClick();
        }

        private void btXoaVong_Click(object sender, EventArgs e)
        {
            if (dgv_list.CurrentRow != null && dgv_list.CurrentRow.Index >= 0 && NumberLib.getInt(dgv_list.CurrentRow.Cells[(int)ContestEnum.RoundID].Value) == 0)
            {
                dgv_list.Rows.Remove(dgv_list.CurrentRow);
                SapXepVongThi();
            }
            else
            {
                if (NumberLib.getInt(dgv_list.CurrentRow.Cells[(int)ContestEnum.RoundID].Value) != 0)
                {
                    if (DBManager.KiemTraDuLieu_Round(NumberLib.getInt(dgv_list.CurrentRow.Cells[(int)ContestEnum.RoundID].Value)))
                    {
                        MessageBox.Show("Không thể xóa vòng thi này được vì đã có dữ liệu !!!", "Thông báo");
                    }
                    else
                    {
                        dgv_list.Rows.Remove(dgv_list.CurrentRow);
                        SapXepVongThi();
                    }
                }
            }
        }

        

        //enum UserEnum { STT, UserID, Username, Fullname, ContestName, SettingName };

        private void btAddUser_Click(object sender, EventArgs e)
        {
            dynamic form = new Form();
            FormAction action = new FormAction(false, true, false, false, false, true);

            form = new gui.category.UserList("Chọn người tham dự", action);
            form.ShowDialog();

            if (form.SelectedItem == null) return;

            object SelectedObject = form.SelectedItem;

            string userID = form.SelectedID.ToString();
            database.User usetitem = DBManager.Detail_User(NumberLib.getInt(userID));

            //String ContestName = Record.ContestName;
            //String SettingName = Record.Setting.SettingName;

            if (NumberLib.getInt(Record.ContestID) == 0)
            {
                MessageBox.Show("Xin vui lòng lưu thông tin trước khi thêm người dự thi", "Thông báo");
                return;
            }


            for (int i = 0; i < dgv_user.Rows.Count; i++)
            {
                if (NumberLib.getInt(dgv_user.Rows[i].Cells[(int)UserEnum.UserID].Value) == NumberLib.getInt(userID))
                {
                    MessageBox.Show("Không thể thêm 1 người 2 lần !!!", "Thông báo");
                    return;
                }
            }
            //enum UserEnum { STT, UserID, ContestUserID, Username, Fullname, ContestName, SettingName };

            dgv_user.Rows.Add(new object[] { 0, userID, 0, usetitem.Username, usetitem.Fullname});

            //for (int i = 0; i < dgv_list.Rows.Count; i++)
            //{
            //    if (RoundCap == NumberLib.getInt(dgv_list.Rows[i].Cells[(int)ContestEnum.RoundCapacity].Value))
            //    {
            //        MessageBox.Show("Không thể tạo vòng thi có số lượng giống nhau !!!", "Thông báo");
            //        return;
            //    }
            //}

            //DateTime timeNow = Global.GetServerDateTime();
            //String StatusX = "A";

            //dgv_list.Rows.Add(new object[] { roundLevel, roundLevel, 0, ID, RoundCap, timeNow, StatusX });
            for (int i = 0; i < dgv_user.Rows.Count; i++)
            {
                dgv_user.Rows[i].Cells[(int)UserEnum.STT].Value = i + 1;
            }
        }

        private void btDeleteUser_Click(object sender, EventArgs e)
        {
            if (dgv_user.CurrentRow != null && dgv_user.CurrentRow.Index >= 0)
            {
                dgv_user.Rows.Remove(dgv_user.CurrentRow);
                //SapXepVongThi();
                for (int i = 0; i < dgv_user.Rows.Count; i++)
                {
                    dgv_user.Rows[i].Cells[(int)UserEnum.STT].Value = i + 1;
                }
            }
        }

        private void bt_suavong_Click(object sender, EventArgs e)
        {
            if (NumberLib.getInt(dgv_list.CurrentRow.Cells[(int)ContestEnum.RoundID].Value) == 0)
            {
                MessageBox.Show("Xin vui lòng lưu thông tin trước khi xem chi tiết", "Thông báo");
                return;
            }

            int RoundID = NumberLib.getInt(dgv_list.Rows[dgv_list.CurrentRow.Index].Cells[(int)ContestEnum.RoundID].Value);

            if (StringLib.isValid(RoundID))
            {
                var form = new gui.contest.RoundDetail(Action, RoundID);
                form.updateButtonUpdate(Status.SelectedValue.ToString() != "A");
                form.ShowDialog();
            }
        }

        private void btn_save_EnabledChanged(object sender, EventArgs e)
        {
            txRoundCap.Enabled = btAddUser.Enabled = btDeleteUser.Enabled = btThemVongMoi.Enabled = btXoaVong.Enabled = btn_save.Enabled;
        }
    }

    public class ContestItem
    {
        public int STT { get; set; }
        public int VongThi { get; set; }
        public int VongID { get; set; }
        public int ContestID { get; set; }
        public int RoundCapacity { get; set; }
        public DateTime DateCreated { get; set; }
        public String Status { get; set; }

        public ContestItem()
        {
            //Contest ID = 0 thì có thể xoá
        }

        public ContestItem(int STT, int Vongthi, int VongID, int ContestID, int RoundCapacity, DateTime DateCreate, String Status)
        {
            this.STT = STT;
            this.VongThi = VongThi;
            this.VongID = VongID;
            this.ContestID = ContestID;
            this.RoundCapacity = RoundCapacity;
            this.DateCreated = (DateTime)DateCreate;
            this.Status = Status;
        }
    }
}

//enum ContestEnum { STT, RoundLevel, RoundID, ContestID, RoundCapacity, DateCreated, Status };

//dgv_list.AutoGenerateColumns = false;
//            Global.InitDataGridView(dgv_list, new DataGridViewColumn[] { 
//                Global.GenColumn("STT").SetAlign(DataGridViewContentAlignment.MiddleCenter).SetFrozen(true).SetVisible(false),
//                Global.GenColumn("Vòng",                            "RoundLevel"),
//                Global.GenColumn("Vòng ID",                         "RoundID").SetVisible(false),
//                Global.GenColumn("ID Constest",                     "ContestID").SetVisible(false),
//                Global.GenColumn("Số lượng hình ảnh cho phép",      "RoundCapacity").SetForeColor(Color.Blue).SetSizeMode(DataGridViewAutoSizeColumnMode.Fill),
//                Global.GenColumn("Ngày tạo",                        "DateCreated").SetFormat("dd/MM/yyyy"),
//                Global.GenColumn("Tình trạng",                      "Status"),
//            });

